//
//  RegisterViewController.m
//  MoXiProject
//
//  Created by 周筱雯 on 2017/6/29.
//  Copyright © 2017年 周筱雯. All rights reserved.
//

#import "RegisterViewController.h"
#import "LoginRegViewModel.h"
#import "PictureRandom.h"
@interface RegisterViewController ()

@property (weak, nonatomic) IBOutlet UIView *registerTxView;

@property (nonatomic,strong) PictureRandom * picRandom;


@property (weak, nonatomic) IBOutlet UITextField *userPhone;
@property (weak, nonatomic) IBOutlet UITextField *userPwd;
@property (weak, nonatomic) IBOutlet UITextField *userAgainPwd;
@property (weak, nonatomic) IBOutlet UITextField *userPic;
@property (weak, nonatomic) IBOutlet UITextField *userCode;
@property (weak, nonatomic) IBOutlet UITextField *userName;

@property (weak, nonatomic) IBOutlet UIButton *btnRegisterClick;
@property (weak, nonatomic) IBOutlet UIButton *btnCodeClick;

@property (nonatomic,strong) LoginRegViewModel * loregViewModel;

@property(nonatomic,strong) NSTimer * timer;
@property (nonatomic,assign)NSInteger  timeNum;               //时间值
@property (nonatomic,copy) NSString * yanzhengmeString;
@property (nonatomic,copy) NSString * strTime;

@end

@implementation RegisterViewController
-(LoginRegViewModel *) loregViewModel{
    if (!_loregViewModel) {
        _loregViewModel = [[LoginRegViewModel alloc] init];
    }
    return _loregViewModel;
}
//计时器
- (NSTimer *)timer
{
    if (!_timer) {
        _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [_timer setFireDate:[NSDate distantFuture]];
    }
    return _timer;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self.navigationItem setTitle:@"注册"];
    [self.view setBackgroundColor:DEF_COLOR_F0F0F0];
    
    self.timeNum = 60;//倒计时时间初始化为60秒
    
    
    /**
     *  图形验证码
     */
    self.picRandom = [[PictureRandom alloc]initWithFrame:CGRectMake(0, 0, self.registerTxView.width, self.registerTxView.height)];
    self.picRandom.fontSize = 20;
    [self.registerTxView addSubview:self.picRandom];
    
    
    /**
     短信验证码
     */
    [[self.btnCodeClick rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        [self sendRequestAndstartTimer];
        
    }];
    
    
    /**
     注册
     */
    
    [[self.btnRegisterClick rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(id x) {
        
        if ([self judgement]) {
            
            [self registerNetWork];
        }
    }];
}


-(void) registerNetWork{

    [MXUtility showMBProgress:self.view message:LoadingText];
    
    [[self.loregViewModel RegisterRequestParameter:self.userPhone.text password:self.userPwd.text userName:self.userName.text code:self.yanzhengmeString strTime:self.strTime
     ] subscribeNext:^(id result) {
        
        if([result[@"errorcode"] integerValue] == 0){
            
            [MXUtility showTips:@"注册成功,前往登录～"];
            [self.navigationController popViewControllerAnimated:YES];
            
        }
        [MXUtility hideMBProgress:self.view];
        
    }error:^(NSError *error) {
        
        [MXUtility hideMBProgress:self.view];
    }];
}

/**
 * 发送获取验证码请求，并且开启计时器
 */
- (void)sendRequestAndstartTimer
{
    //检查出不符合要求的手机号
    @weakify(self);
    if(self.userPhone.text.length == 0){
        [MXUtility showTips:@"手机号不能为空"];
        return;
    }else if(![MXUtility validateMobile:self.userPhone.text]) {
        [MXUtility showTips:@"请输入正确的手机号"];
        return;
    }else{
        self.btnCodeClick.enabled = NO;
        [self.btnCodeClick setTitle:@"获取中..." forState:UIControlStateDisabled];
        @strongify(self);
        
        [MXUtility showMBProgress:self.view message:LoadingText];
        
        [[self.loregViewModel sendvaliRequestParameter:self.userPhone.text] subscribeNext:^(id result) {
            
            
            self.yanzhengmeString = result[@"result"][@"code"];
            self.strTime = result[@"result"][@"strTime"];
            
            [self startTimer];
            
            [MXUtility hideMBProgress:self.view];
            
        }error:^(NSError *error) {
            
            [MXUtility hideMBProgress:self.view];
            
            self.btnCodeClick.enabled = YES;
            self.timeNum = 60;
            [self.btnCodeClick setTitle:@"重新获取" forState:UIControlStateDisabled];
        }];
    }
}

/**
 * 倒计时1
 */
- (void)startTimer
{
    [self.btnCodeClick setTitle:[NSString stringWithFormat:@"%ld s",(long)self.timeNum] forState:UIControlStateDisabled];
    [self.timer setFireDate:[NSDate distantPast]];
}
/**
 * 倒计时2
 */
- (void)timerAction
{
    self.timeNum--;
    
    [self.btnCodeClick setTitle:[NSString stringWithFormat:@"%ld s",(long)self.timeNum] forState:UIControlStateDisabled];
    
    if (self.timeNum == 0) {
        //暂停计时器
        [_timer setFireDate:[NSDate distantFuture]];
        [_timer invalidate];
        _timer = nil;
        self.btnCodeClick.enabled = YES;
        self.timeNum = 60;
        [self.btnCodeClick setTitle:@"重新获取" forState:UIControlStateDisabled];
    }
}


-(BOOL) judgement{
    
    //判断是否非空
    if ([MXUtility NSNULLString:self.userPhone.text]) {
        [MXUtility showTips:@"手机号不能为空"];
        return false;
    }
    if (![MXUtility validateMobile:self.userPhone.text]) {
        [MXUtility showTips:@"请输入正确的手机号"];
        return false;
    }
    if ([MXUtility NSNULLString:self.userPwd.text]) {
        [MXUtility showTips:@"密码不能为空"];
        return false;
    }
    if (![MXUtility CheckInput:self.userPwd.text]) {
        [MXUtility showTips:@"请输入正确的密码"];
        return false;
    }
    if ([MXUtility NSNULLString:self.userAgainPwd.text]) {
        [MXUtility showTips:@"确认密码不能为空"];
        return false;
    }
    if ((![self.userPwd.text isEqualToString:self.userAgainPwd.text])) {
        [MXUtility showTips:@"两次输入密码不一致"];
        return false;
    }
    if ([MXUtility NSNULLString:self.userPic.text]) {
        [MXUtility showTips:@"图形验证码不能为空"];
        return false;
    }
    if (![self.picRandom startAuthWithString:self.userPic.text]) {
        [MXUtility showTips:@"图形验证码错误"];
        return false;
    }
    if ([MXUtility NSNULLString:self.userCode.text]) {
        [MXUtility showTips:@"短信验证码不能为空"];
        return false;
    }
    if (![self.yanzhengmeString isEqualToString:self.userCode.text]) {
        [MXUtility showTips:@"短信验证码不正确"];
        return false;
    }
    if ([MXUtility NSNULLString:self.userName.text]) {
        [MXUtility showTips:@"用户名不能为空"];
        return false;
    }
    
    return true;
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.userPhone resignFirstResponder];
    [self.userPic resignFirstResponder];
    [self.userPwd resignFirstResponder];
    [self.userCode resignFirstResponder];
    [self.userName resignFirstResponder];
    [self.userAgainPwd resignFirstResponder];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
